package ar.uba.fi.taller2.ftrs.index;

import java.io.*;
import java.util.*;
import ar.uba.fi.taller2.ftrs.tree.*;

public class IndexadorImp
{
   private long indexptr=0;

   static { System.load("/home/martin/workspace/magios/src/ar/uba/fi/taller2/ftrs/index/libindex.so"); }
   
   private native long create(String dataPath, boolean mode);

   private native long create(String dataPath, int n);

   private native void destroy(long instance);
   
   private native void generarIndice(long instance);

   private native long nuevoDocumento( String str, long instance);

   private native long insertarTermino( String str, long instance);
   
   private native int[] getDocs(int offset, int frec, long instance);

   private void updateTree(String termino, int offsetDocFrec, int frec) {
	   
	   BSTree tree = BSTree.getBPTree();
	   tree.addKey(termino, offsetDocFrec, frec);
	   System.out.println("Termino: "+termino+", Offset: "+offsetDocFrec+", Offset: "+frec);
   }

   public IndexadorImp(String dataPath, boolean mode) throws IOException
   {
	   super();

	   File dir = new File(dataPath);
	   if (!dir.exists()) {
		   throw new IOException("Error, no existe el directoio: "+ dataPath);
	   }

	   this.indexptr = create(dataPath, mode);
   }

   public IndexadorImp(String dataPath, int c) throws IOException
     {
      super();
      
      File dir = new File(dataPath);
	   if (!dir.exists()) {
		   throw new IOException("Error, no existe el directoio: "+ dataPath);
	   }
      
      this.indexptr = create(dataPath, c);
     }

   public void destroy()
     {
      destroy( this.indexptr );
     }

   public long nuevoDocumento(String nombre)
     {
       return nuevoDocumento( nombre,this.indexptr );
     }

   public long insertarTermino( String term)
     {
       return insertarTermino( term, this.indexptr );
     }

   public void generarIndice()
	{
	   generarIndice(this.indexptr);
	   BSTree tree = BSTree.getBPTree();
	   tree.printXML();
	   try {
		   tree.finalize();
	   } catch (Throwable e) {
		   // TODO Auto-generated catch block
		   e.printStackTrace();
	   }
	}

   private int[] getDocs(int offset, int frec) {
	   
	   return getDocs( offset, frec, this.indexptr );
   }
   
   public int[] getDocs(String termino) {
	   
	   BSTree tree = BSTree.getBPTree();
	   
	   ArrayList<Integer> array = tree.getValue(termino);
	   if (array != null && array.size() >= 2)
		   return getDocs(array.get(0), array.get(1));
		   //return getDocs(0, 1);
	   else
		   return null;
   }
}
